#!/usr/bin/env python
import os,sys,time,timeit,os.path,threading,string
from subprocess import *
from datetime import datetime


class restart(threading.Thread):
    def run(self):
        output = Popen("ps aux | grep capture.sh", shell=True, stdout=PIPE).stdout
        output = output.read()
        output=output.strip()
        id=output.split(" ")
        i = 0 
        killid=id[5]
        print killid
        print os.system('kill '+str(killid))
        print os.system('kill '+str(int(killid)+1))
        print os.system('kill '+str(int(killid)+2))
        os.system("sh ~/Pictures/capture.sh")
class Monitor(threading.Thread):
    def run(self):
        while 1:
            output = Popen("ls -l ~/Pictures/", shell=True, stdout=PIPE).stdout
            s = output.readlines()
            for lines in s:
                if '0.raw' in lines:
                    raw=lines[-12:-7]
                    t=str(datetime.now())
                    e=t[11:16]
                    if raw==e:
                        print 'pass'
                        pass
                    else:
                        restart().start()
            time.sleep(15)
class Start(threading.Thread):
    def run(self):
        print os.getpid()
        os.system("sh ~/Pictures/capture.sh")
class Mirror(threading.Thread):
    def run(self):
        if mode=="1" and connect=="w" and compression=="n":
            ## rgb convert
            atrix="nc -l 9000 > ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt bgr32 -s 540x960 \-i - ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            #xperia x10 & g1 rgb convert
            xperia="nc -l 9000 > ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb565 -s 480x854 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            ##Nexus S rgb convert
            nexuss="nc -l 9000 > ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb32 -s 480x800 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            if device == "Atrix" or device=='atrix':
                standard=atrix
            if device == "X10" or device=='x10':
                standard=xperia
            if device == "NexusS" or "nexuss":
                standard=nexuss
            script="while true; do "+standard+";done"
            q=open("/home/"+user+"/Pictures/capture.sh",'w').write(script)
            os.system('touch ~/Pictures/0.png')
            Start().start()
            #Monitor().start()
            print "Opening Chrome, Refresh page if no image appears"
            time.sleep(5)
            g=os.system('google-chrome ~/Pictures/video.html')
            if g <= 0:
                print "Opening Firefox, Refresh page if no image appears"
            else:
                os.system('firefox video.html')
        if mode=="1" and connect=="w" and compression=="y":
            ##atrix rgb convert
            atrix="nc -1 9000 | zcat > ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt bgr32 -s 540x960 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            #xperia x10 & g1 rgb convert
            xperia="nc -1 9000 | zcat > ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb565 -s 480x854 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            ##Nexus S rgb convert
            nexuss="nc -l 9000 | zcat > ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb32 -s 480x800 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            if device == "Atrix":
                standard=atrix
            if device == "atrix":
                standard=atrix
            if device == "X10":
                standard=xperia
            if device == "x10":
                standard=xperia
            if device == "NexusS" or "nexuss":
                standard=nexuss
            script="while true; do "+standard+";done"
            q=open("/home/"+user+"/Pictures/capture.sh",'w').write(script)
            os.system('touch ~/Pictures/0.png')
            Start().start()
            #Monitor().start()
            print "Opening Chrome, Refresh page if no image appears"
            time.sleep(5)
            g=os.system('google-chrome ~/Pictures/video.html')
            if g <= 0:
                print "Opening Firefox, Refresh page if no image appears"
            else:
                os.system('firefox video.html')
                        
        if mode=="2" and connect=="w" and compression=="n":
            if device=="atrix" or device=="Atrix":
                standard="w=540:h=960:format=rgb32"
            if device=="X10" or device=="x10":
                xperia="w=480:h=854:i420:format=rgb32"
            if device=="nexuss" or device=="Nexuss":
                standard="w=480:h=800:i420:format=rgb32"
            os.system("(while true; do nc -l 9000; done) | mplayer -demuxer rawvideo -rawvideo "+standard+" -nosound - ")
            
        if mode=="2" and connect=="w" and compression=="y":
            if device=="atrix" or device=="Atrix":
                standard="w=540:h=960:i420:format=rgb32"

            if device=="X10" or device=="x10":
                xperia="w=480:h=854:i420:format=rgb32"

            if device=="nexuss" or device=="Nexuss":
                standard="w=480:h=800:i420:format=rgb32"
                s='480x800'
            os.system("while true; do nc -l 9000; done | zcat | mplayer -demuxer rawvideo -rawvideo "+standard+" -nosound - ")
        if mode=='3' and connect=='w' and compression=='n':
            if device=="atrix" or device=="Atrix":
                standard="bgr32 -s 540x960"
            if device=="X10" or device=="x10":
                xperia="rgb565 -s 480x854"
            if device=="nexuss" or device=="Nexuss":
                standard="rgb32 -s 480x800"
            os.system("while true; do nc -l 9000;done | ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt "+standard+" -i - -f mpeg2video - | vlc -")
        if mode=='3' and connect=='w' and compression=='y':
            if device=="atrix" or device=="Atrix":
                standard="bgr32 -s 540x960"
            if device=="X10" or device=="x10":
                xperia="rgb565 -s 480x854"
            if device=="nexuss" or device=="Nexuss":
                standard="rgb32 -s 480x800"
            os.system("while true; do nc -l 9000;done | zcat | ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt "+standard+" -i - -f mpeg2video - | vlc - ")
        if mode=='3' and connect=='a':
            if device=="atrix" or device=="Atrix":
                standard="bgr32 -s 540x960"
            if device=="X10" or device=="x10":
                xperia="rgb565 -s 480x854"
            if device=="nexuss" or device=="Nexuss":
                standard="rgb32 -s 480x800"
            os.system("while true; do /home/"+user+"/android-sdk-linux_86/platform-tools/adb shell fbread ;done | ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt "+standard+" -i - -f mpeg2video - | vlc -")

        if mode=="2" and connect=="a":
            if device=="atrix" or device=="Atrix":
                standard="w=540:h=960:format=rgb32"
            if device=="X10" or device=="x10":
                xperia="w=480:h=854:i420:format=rgb32"
            if device=="nexuss" or device=="Nexuss":
                standard="w=480:h=800:i420:format=rgb32"
            os.system("while true; do /home/"+user+"/android-sdk-linux_86/platform-tools/adb shell fbread ;done | mplayer -demuxer rawvideo -rawvideo "+standard+" -cache 4096 -fixed-vo -nosound - ")
        if mode=="1" and connect=="a":
            ##atrix rgb convert
            atrix="/home/"+user+"/android-sdk-linux_86/platform-tools/adb shell 'fbread > /sdcard/frame.raw';/home/"+user+"/android-sdk-linux_86/platform-tools/adb pull /sdcard/frame.raw /home/"+user+"/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt bgr32 -s 540x960 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            #xperia x10 & g1 rgb convert
            xperia="/home/"+user+"/android-sdk-linux_86/platform-tools/adb shell 'cat /dev/graphics/fb0 > /sdcard/frame.raw';/home/"+user+"/android-sdk-linux_86/platform-tools/adb pull /sdcard/frame.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb565 -s 480x854 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            ##Nexus S rgb convert
            nexuss="/home/"+user+"/android-sdk-linux_86/platform-tools/adb shell 'cat /dev/graphics/fb0 > /sdcard/frame.raw';/home/"+user+"/android-sdk-linux_86/platform-tools/adb pull /sdcard/frame.raw ~/Pictures/0.raw && ffmpeg -vcodec rawvideo -f rawvideo -pix_fmt rgb32 -s 480x800 \-i ~/Pictures/0.raw -f image2 -vcodec png ~/Pictures/0.png"
            if device == "Atrix" or device=='atrix':
                standard=atrix
            if device == "X10" or device=='x10':
                standard=xperia
            if device == "NexusS" or device=="nexuss":
                standard=nexuss
            script="while true; do "+standard+";done"
            q=open("/home/"+user+"/Pictures/capture.sh",'w').write(script)
            os.system('touch ~/Pictures/0.png')
            Start().start()
            #Monitor().start()
            print "Opening Chrome, Refresh page if no image appears"
            time.sleep(5)
            g=os.system('google-chrome ~/Pictures/video.html')
            if g <= 0:
                print "Opening Firefox, Refresh page if no image appears"
            else:
                os.system('firefox video.html')
class stream(threading.Thread):
    def run(self):
        os.system("nc -l 9003 | mplayer -fixed-vo - ")
        stream().start()
        sys.exit()
class lxstream(threading.Thread):
    def run(self):
        config = Popen("nc -l 9001", shell=True, stdout=PIPE).stdout
        run = config.readlines()
        run=run[0].strip()
        print run
        os.system('while true; do nc '+phonewifi+' 9001; done | '+run)
        print "Make sure to start GroundWork on the device"
        lxstream().start()
        sys.exit()
class type(threading.Thread):
    def run(self):
        n=0
        while True:
            os.system('nc -l 9001 > ground.work')
            try:
                status = open('ground.work','r').readlines()
                time.sleep(1)
                if status[0].strip()=='file':
                    print "Streaming File"
                    os.system('rm ground.work')
                    type().start()
                    stream()
                    sys.exit()
                if status[0].strip()=='mirror':
                    Mirror.start()
            except:
                n=n+1
                print 'exception',n
                time.sleep(5)
                


def setup():
    global user,device,phonewifi,mode,connect,compression
    print "Please save your settings this time"
    person = Popen("whoami", shell=True, stdout=PIPE).stdout
    person = person.read()
    user=person.strip()
    phonewifi=raw_input('What is the Android/Meego device ip address: ')
    device=raw_input("Atrix or X10 or NexusS or N9: ")
    if device=='n9' or device=='N9':
        a=open("config.txt",'w').write(user+'\n'+phonewifi+'\n'+device)
        lxstream().start()
    else:
        mode=raw_input("Browser(1) or Mplayer(2) or VLC(3): ")
        connect=raw_input("Use Wifi(W) or usb(adb required to be installed and in path(A))")
        compression='n'
        compression=raw_input('Use Compression over wifi?(Use for slow wifi Networks) (y or n)')
        save=raw_input("Do you want to save your settings? (y or n) ")
        if save=="y" or "Y":
            a=open("config.txt",'w').write(user+'\n'+phonewifi+'\n'+device+'\n'+mode+'\n'+connect+'\n'+compression)

reset=raw_input('Do you want to use saved settings? (y or n)')
if reset=='n' or reset=='N':
    setup()
else:
    b=open('config.txt','r').readlines()
    user=b[0].strip()
    phonewifi=b[1].strip()
    device=b[2].strip()
    if device=='n9' or device=='N9':
        lxstream().start()
        sys.exit()
    mode=b[3].strip()
    connect=b[4].strip()
    compression=b[5].strip()
    if mode=="1":
        print 'User: ',user    +'\n','Wifi: ',phonewifi    +'\n','Device: ',device    +'\n','OutputMode: Browser'+'\n','Compression on ?: ',compression
    if mode=="2":
        print 'User: ',user    +'\n','Wifi: ',phonewifi    +'\n','Device: ',device    +'\n','OutputMode: Mplayer'+'\n','Compression on ?: ',compression
    if mode=='3':
        print 'User: ',user    +'\n','Wifi: ',phonewifi    +'\n','Device: ',device    +'\n','OutputMode: VLC'+'\n','Compression on ?: ',compression


html="""
<html>
<head>
</head>
<body>
<p>
<img src="0.png" id="reloader" onload="setTimeout('document.getElementById(\'reloader\').src=\'0.png?\'+new Date().getMilliseconds()', 900)" />
</p>
</body>
</html>
    """
            
if device=='n9' or device=='N9':
    sys.exit()
else:
    c = os.system("test -e video.html && echo 'testing for video file'")
if c !=0:
    F=open('video.html','w').write(html)    
Mirror().start()
stream().start()


    


